package controllers

import (
	"github.com/astaxie/beego"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
)

type WebSocketController struct {
	beego.Controller
}

var clients = make(map[*websocket.Conn]bool) // 连接的客户端
var broadcast = make(chan Message)           // 广播信道

func (this *WebSocketController) WebSocketResponse() {
	ws, err := websocket.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(this.Ctx.ResponseWriter, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		beego.Error("Cannot setup WebSocket connection:", err)
		return
	}

	// 添加到在线列表
	Connect(ws)
	defer Leave(ws)

	// 循环获取用户提交的数据 转为struct
	for {
		var msg Message
		// 读信息 将json字符串转映射到结构体上
		err := ws.ReadJSON(&msg)
		if err != nil {
			log.Printf("error: %v", err)
			delete(clients, ws)
			break
		}
		// 将新接收的消息发送到广播信道
		broadcast <- msg
	}
}
